<script setup>
import seckillResultApi from '@/api/seckill/seckillResult_api.js'
import seckillGoodsApi from '@/api/seckill/seckillGoods_api.js'
import seckillActivityApi from '@/api/seckill/seckillActivity_api.js'
import userApi from '@/api/user_api.js'
import goodsApi from '@/api/goods_api.js'
import { ref, onMounted } from "vue"
import { ElMessageBox, ElMessage } from "element-plus"
import lodash from 'lodash'

//定义绑定的数据
//表格中的数据
const tableData = ref([]);
const total = ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);

// 商品信息缓存
const goodsMap = ref(new Map());
// 活动信息缓存
const activityMap = ref(new Map());
// 用户信息缓存
const userMap = ref(new Map());
// 秒杀商品信息缓存
const seckillGoodsMap = ref(new Map());

//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  username: '',
  goods_name: '',
  activity_name: '',
  result: '',
});

// 实际传给后端的查询参数
const backendSearchParams = ref({
  current: 1,
  limit: 10,
  user_id: '',
  seckill_goods_id: '',
  activity_id: '',
  result: '',
});

//要修改的数据
const obj = ref({});

const search = async () => {
  try {
    // 更新实际传给后端的参数
    backendSearchParams.value.current = searchObj.value.current;
    backendSearchParams.value.limit = searchObj.value.limit;

    console.log('发送的查询参数:', backendSearchParams.value);
    var result = await seckillResultApi.getResultPage(
        backendSearchParams.value.current,
        backendSearchParams.value.limit,
        backendSearchParams.value
    );
    console.log('收到的响应数据:', result);

    // 检查返回的数据结构
    if (result && typeof result === 'object') {
      // 如果返回的是直接的分页数据
      if (result.records && Array.isArray(result.records)) {
        tableData.value = result.records;
        total.value = result.total || 0;

        // 获取关联信息
        await fetchRelatedInfo(result.records);
      }
      // 如果返回的是包含data字段的对象（Result包装）
      else if (result.data && result.data.records && Array.isArray(result.data.records)) {
        tableData.value = result.data.records;
        total.value = result.data.total || 0;

        // 获取关联信息
        await fetchRelatedInfo(result.data.records);
      }
      // 其他情况
      else {
        tableData.value = [];
        total.value = 0;
      }
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取秒杀结果列表时出错:', error);
    if (error.response) {
      if (error.response.status === 404) {
        ElMessage.error('API接口未找到，请检查后端服务是否正常运行且API路径配置正确');
      } else if (error.response.status === 500) {
        ElMessage.error('服务器内部错误，请联系管理员');
      } else {
        ElMessage.error(`请求失败: ${error.response.status} ${error.response.statusText}`);
      }
    } else if (error.request) {
      ElMessage.error('无法连接到服务器，请检查网络连接和后端服务是否运行');
    } else {
      ElMessage.error('请求失败: ' + error.message);
    }
    tableData.value = [];
    total.value = 0;
  }
}

// 获取关联信息
const fetchRelatedInfo = async (resultList) => {
  try {
    // 收集还未缓存的秒杀商品ID
    const seckillGoodsIdsToFetch = resultList
        .map(item => item.seckill_goods_id)
        .filter(id => id && !seckillGoodsMap.value.has(id));

    // 批量获取秒杀商品信息以及对应的商品信息
    for (const id of seckillGoodsIdsToFetch) {
      try {
        const seckillGoodsInfo = await seckillGoodsApi.getSeckillGoodsById(id);
        if (seckillGoodsInfo && seckillGoodsInfo.data) {
          seckillGoodsMap.value.set(id, seckillGoodsInfo.data);
          // 获取对应的商品信息
          const goodsInfo = await goodsApi.getGoodsById(seckillGoodsInfo.data.goods_id);
          if (goodsInfo && goodsInfo.data) {
            goodsMap.value.set(id, goodsInfo.data);
          } else if (goodsInfo && typeof goodsInfo === 'object') {
            goodsMap.value.set(id, goodsInfo);
          }
        } else if (seckillGoodsInfo && typeof seckillGoodsInfo === 'object' && seckillGoodsInfo.goods_id) {
          seckillGoodsMap.value.set(id, seckillGoodsInfo);
          // 获取对应的商品信息
          const goodsInfo = await goodsApi.getGoodsById(seckillGoodsInfo.goods_id);
          if (goodsInfo && goodsInfo.data) {
            goodsMap.value.set(id, goodsInfo.data);
          } else if (goodsInfo && typeof goodsInfo === 'object') {
            goodsMap.value.set(id, goodsInfo);
          }
        }
      } catch (error) {
        console.error(`获取秒杀商品ID ${id} 信息失败:`, error);
      }
    }

    // 收集还未缓存的活动ID
    const activityIdsToFetch = resultList
        .map(item => item.activity_id)
        .filter(id => id && !activityMap.value.has(id));

    // 批量获取活动信息
    for (const id of activityIdsToFetch) {
      try {
        const activityInfo = await seckillActivityApi.getActivityById(id);
        if (activityInfo && activityInfo.data) {
          activityMap.value.set(id, activityInfo.data);
        } else if (activityInfo && typeof activityInfo === 'object') {
          activityMap.value.set(id, activityInfo);
        }
      } catch (error) {
        console.error(`获取活动ID ${id} 信息失败:`, error);
      }
    }

    // 收集还未缓存的用户ID
    const userIdsToFetch = resultList
        .map(item => item.user_id)
        .filter(id => id && !userMap.value.has(id));

    // 批量获取用户信息
    for (const id of userIdsToFetch) {
      try {
        const userInfo = await userApi.getUserById(id);
        if (userInfo && userInfo.data) {
          userMap.value.set(id, userInfo.data);
        } else if (userInfo && typeof userInfo === 'object') {
          userMap.value.set(id, userInfo);
        }
      } catch (error) {
        console.error(`获取用户ID ${id} 信息失败:`, error);
      }
    }
  } catch (error) {
    console.error('获取关联信息时出错:', error);
  }
}

//页面加载后要挂载的数据
onMounted(async () => {
  await search();
});

//重置查询条件
const resetSearch = () => {
  searchObj.value.username = '';
  searchObj.value.goods_name = '';
  searchObj.value.activity_name = '';
  searchObj.value.result = '';
  searchObj.value.current = 1;
  searchObj.value.limit = 10;
  backendSearchParams.value.user_id = '';
  backendSearchParams.value.seckill_goods_id = '';
  backendSearchParams.value.activity_id = '';
  backendSearchParams.value.result = '';
  search();
}

//分页查询用
const handleSizeChange = () => {
  searchObj.value.current = 1; // 页大小改变时回到第一页
  search();
}

//分页查询用
const handleCurrentChange = () => {
  search(); // 只需要重新搜索，参数已经在search函数中同步
}

//定义方法
const handlerSearch = async () => {
  searchObj.value.current = 1;

  // 如果有用户名查询条件，先查询用户ID
  if (searchObj.value.username) {
    try {
      // 使用用户分页接口查找用户
      const userResult = await userApi.getUserPage(1, 100, { username: searchObj.value.username });
      if (userResult && userResult.records && userResult.records.length > 0) {
        // 找到匹配的用户，使用第一个匹配用户的ID进行查询
        backendSearchParams.value.user_id = userResult.records[0].id;
      } else {
        // 没有找到匹配的用户，设置一个不可能存在的用户ID
        backendSearchParams.value.user_id = -1;
      }
    } catch (error) {
      console.error('查询用户信息失败:', error);
      ElMessage.error("查询用户信息失败");
      return;
    }
  } else {
    backendSearchParams.value.user_id = '';
  }

  // 如果有商品名称查询条件，先查询商品ID，再通过商品ID查询秒杀商品ID
  if (searchObj.value.goods_name) {
    try {
      // 使用商品分页接口查找商品
      const goodsResult = await goodsApi.getGoodsPage(1, 100, { name: searchObj.value.goods_name });
      if (goodsResult && goodsResult.records && goodsResult.records.length > 0) {
        // 找到匹配的商品，使用第一个匹配商品的ID查询对应的秒杀商品
        const goodsId = goodsResult.records[0].id;

        // 通过goods_id查找对应的秒杀商品
        const seckillGoodsResult = await seckillGoodsApi.getSeckillGoodsByGoodsId(goodsId);
        if (seckillGoodsResult || seckillGoodsResult.data) {
          // 找到对应的秒杀商品ID
          backendSearchParams.value.seckill_goods_id = seckillGoodsResult.id;
        } else if (seckillGoodsResult && Array.isArray(seckillGoodsResult) && seckillGoodsResult.length > 0) {
          // 如果返回的是数组，取第一个
          backendSearchParams.value.seckill_goods_id = seckillGoodsResult[0].id;
        } else {
          // 没有找到对应的秒杀商品，设置一个不可能存在的秒杀商品ID
          backendSearchParams.value.seckill_goods_id = -1;
        }
      } else {
        // 没有找到匹配的商品，设置一个不可能存在的秒杀商品ID
        backendSearchParams.value.seckill_goods_id = -1;
      }
    } catch (error) {
      console.error('查询秒杀商品信息失败:', error);
      ElMessage.error("查询秒杀商品信息失败");
      return;
    }
  } else {
    backendSearchParams.value.seckill_goods_id = '';
  }

  // 如果有活动名称查询条件，先查询活动ID
  if (searchObj.value.activity_name) {
    try {
      // 使用活动分页接口查找活动
      const activityResult = await seckillActivityApi.getActivityPage(1, 100, { name: searchObj.value.activity_name });
      if (activityResult && activityResult.records && activityResult.records.length > 0) {
        // 找到匹配的活动，使用第一个匹配活动的ID进行查询
        backendSearchParams.value.activity_id = activityResult.records[0].id;
      } else {
        // 没有找到匹配的活动，设置一个不可能存在的活动ID
        backendSearchParams.value.activity_id = -1;
      }
    } catch (error) {
      console.error('查询活动信息失败:', error);
      ElMessage.error("查询活动信息失败");
      return;
    }
  } else {
    backendSearchParams.value.activity_id = '';
  }

  // 处理结果查询条件
  backendSearchParams.value.result = searchObj.value.result;

  search();
}

//编辑对话框的取消按钮点击事件
const editCancel = () => {
  obj.value = {};//清空数据
  editWinVisible.value = false;//关闭对话框
}

//编辑对话框的提交按钮点击事件
const editCommit = async () => {
  try {
    const result = await seckillResultApi.updateResult(obj.value);//提交修改数据
    console.log('编辑返回结果:', result);

    if (result && (result.code === 200 || !result.code)) {
      ElMessage.success('更新成功');
      await search();//刷新表格
      editWinVisible.value = false;//关闭编辑对话框
    } else {
      ElMessage.error(result?.message || '更新失败');
    }
  } catch (error) {
    console.error('更新失败:', error);
    ElMessage.error('更新失败: ' + (error.response?.data || error.message));
  }
}

const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
  console.log(index, row)
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        try {
          const result = await seckillResultApi.deleteResult(row.id);
          if (result && (result.code === 200 || !result.code)) {
            ElMessage.success('删除成功');
            //重新加载数据
            searchObj.value.current = 1;
            await search();
          } else {
            ElMessage.error(result.message || '删除失败');
          }
        } catch (error) {
          ElMessage.error('删除失败: ' + error.message);
        }
      })
      .catch(() => {
      })
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  return dateTimeStr.replace('T', ' ');
}

// 格式化结果显示
const formatResult = (result) => {
  switch (result) {
    case 1:
      return '成功';
    case 0:
      return '失败';
    default:
      return '未知';
  }
}

// 获取结果标签类型
const getResultType = (result) => {
  switch (result) {
    case 1:
      return 'success';
    case 0:
      return 'danger';
    default:
      return 'info';
  }
}

// 根据秒杀商品ID获取商品名称 (模仿orderAddr页面的处理逻辑)
const getGoodsNameBySeckillGoodsId = (seckillGoodsId) => {
  if (!seckillGoodsId) return '';

  // 从商品映射中获取商品名称
  const goodsInfo = goodsMap.value.get(seckillGoodsId);
  return goodsInfo && goodsInfo.name ? goodsInfo.name : '';
}

// 根据活动ID获取活动名称
const getActivityName = (id) => {
  if (!id) return '';

  const activityInfo = activityMap.value.get(id);
  return activityInfo && activityInfo.name ? activityInfo.name : '';
}

// 根据用户ID获取用户名
const getUserName = (id) => {
  if (!id) return '';

  const userInfo = userMap.value.get(id);
  return userInfo && userInfo.username ? userInfo.username : '';
}
</script>

<template>
  <div class="seckill-result-management">
    <h2>秒杀结果管理</h2>

    <div class="tips-container">
      <el-alert
          title="请输入完整的名称，否则会查询不到"
          type="info"
          show-icon
          size="small"
          class="search-tip"
          :closable="false"
      />
    </div>

    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
      <el-form-item label="用户名">
        <el-input
            v-model="searchObj.username"
            placeholder="请输入用户名"
            clearable
        />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input
            v-model="searchObj.goods_name"
            placeholder="请输入商品名称"
            clearable
        />
      </el-form-item>
      <el-form-item label="活动名称">
        <el-input
            v-model="searchObj.activity_name"
            placeholder="请输入活动名称"
            clearable
        />
      </el-form-item>
      <el-form-item label="结果">
        <el-select v-model="searchObj.result" placeholder="请选择结果" clearable>
          <el-option label="成功" value="1"></el-option>
          <el-option label="失败" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="结果ID"></el-table-column>
      <el-table-column prop="user_id" label="用户">
        <template #default="scope">
          {{ getUserName(scope.row.user_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="seckill_goods_id" label="商品名称">
        <template #default="scope">
          {{ getGoodsNameBySeckillGoodsId(scope.row.seckill_goods_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="activity_id" label="活动名称">
        <template #default="scope">
          {{ getActivityName(scope.row.activity_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="result" label="结果">
        <template #default="scope">
          <el-tag :type="getResultType(scope.row.result)">
            {{ formatResult(scope.row.result) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="seckill_time" label="秒杀时间">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.seckill_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理按钮">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10,20,30,50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!--编辑对话框-->
    <el-dialog v-model="editWinVisible" title="编辑秒杀结果" width="500">
      <el-form :model="obj">
        <el-form-item label="用户ID" :label-width="100">
          <el-input v-model.number="obj.user_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="秒杀商品ID" :label-width="100">
          <el-input v-model.number="obj.seckill_goods_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="活动ID" :label-width="100">
          <el-input v-model.number="obj.activity_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="结果" :label-width="100">
          <el-select v-model="obj.result" placeholder="请选择结果">
            <el-option label="成功" :value="1"></el-option>
            <el-option label="失败" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.seckill-result-management {
  padding: 20px;
  background-color: #fff;
}

.seckill-result-management h2 {
  margin-bottom: 20px;
}

.tips-container {
  margin-bottom: 15px;
}
</style>
